# -*- coding: utf8 -*-
# reload.py
"""
Function attributes:
* load: boolean. Optional. If False the function will not load.
* name: string. Optional.
* priority: string. Optional. Three values are available: "high", "medium" or "low",
  default value: "medium".
* thread: boolean. Optional. If True, function will work by starting a thread.
* rule: string or regexp object. Required.
* aliases: list of string or regexp objects. Optional.
* fullmsg: boolean. Optional. If True, pattern is searched on whole message, else
  pattern is a command, the message must begin with a sign.

* access
* evttypes
* ignore
* limit: maximum number of requests in 1 minute.
* channels
* url
"""
field = "botops"

import imp, os, re, time
from random import randint, choice

from core.optimizers import _path, Load, File
from core.ircfuncs import *

def reboot_(bot, evt, cmd):
	if not has_access(bot, reboot_.level, evt): return
	msg = u"Ara torne :) ..."
	from_ = evt.target or bot.features.network()
	msg=cmd.dict["msg"] if hasattr(evt, "dict") and cmd.dict.get("msg") else "%s m'ho ha demanat des de %s" % (evt.source, from_)
	bot.reboot(msg)
reboot_.rule = re.compile(r"^(?:(?:$both)?reboot)!?(?: (?P<msg>.*))?$")
reboot_.fullmsg = True
reboot_.level = "admin"

def reload_(bot, evt, cmd):
	if not has_access(bot, reload_.level, evt): return
	if not isinstance(cmd.opts['lang'], bool):
		t=time.time()
		import lang
		langfile = cmd.opts['lang']

		langfiles = _path.join(_path.home, "lang")
		if not langfile:
			bot.priv_notice("module name expected")
			return
		elif "%s.py" % langfile not in os.listdir(langfiles):
			bot.priv_notice("unknown module")
			return

		if isinstance(cmd.opts['lang'], unicode):
			execfile(_path.join(langfiles, "%s.py" % langfile))
			t=time.time()-t
			bot.reply(evt, "reloaded lang.%s in %0.4f ms" % (cmd.opts['lang'], t))
		elif isinstance(cmd.opts['lang'], list):
			for langfile in cmd.opts['lang']:
				try:
					execfile(_path.join(langfiles, "%s.py" % langfile))
				except AttributeError:
					bot.priv_notice("module %s not found", l)
			t=time.time()-t
			langs=", ".join(cmd.opts['lang'])
			bot.priv_notice("reloaded %s langs in %.3f ms", langs, t)
		if not cmd.opts.arguments(): return

	if cmd.action == 'replies':
		bot.replies = File("replies.py", "speech").load()
		bot.reply(evt, "module has been reloaded.")
		return

	if cmd.arguments == "bot":
		import bot
		exec("reload(bot)")
		bot.reply(evt, "bot has been reloaded")
		return

	short_names={
		"fr": "freenode",
		"wm": "wikimedia",
		"cm": "common"
	}
	if "." in cmd.arguments:
		folder, name = cmd.arguments.split(".")
		folder = short_names[folder] if folder in short_names else bot.features.network()
	else:
		folder = bot.features.network().lower()
		name = cmd.arguments

	modules = _path.join(_path.home, "commands", folder)
	if not name:
		bot.priv_notice(evt, "module name expected")
		return
	elif "%s.py" % name not in os.listdir(modules):
		bot.priv_notice(evt, "unknown module")
		return
	module = File("%s.py" % name, modules).load()

	field = module.field if hasattr(module, "field") else name
	if folder == "wikimedia":
		bot = bot.bots(("slave", 1))
	begin = time.time()
	bot.load._register(vars(module), name, field)
	bot.load._bindrules()
	for priority in bot.commands:
		bot.commands[priority].update(bot.load.commands[priority])
	chrono = time.time() - begin

	if hasattr(module, '__file__'):
		mtime = os.path.getmtime(module.__file__)
		modified = time.strftime('%Y-%m-%d %H:%M:%S', time.gmtime(mtime))
	else: modified = 'unknown'
	msg = bot._translate(evt, '%r &B;(version: %s)&N; reloaded in %.3f ms.')
	msg = msg % (module, modified, chrono)
	if bot != bot.bots(("master", 0)):
		bot = bot.bots(("master", 0))
	bot.reply(evt, msg.replace(r"iShare{sep}SugarSync{sep}my Python scripts".format(sep=os.path.sep), "..."))
reload_.rule = "reload"
reload_.level = "tester"
